package com.gopay.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.ipay.ebank.IpayMessage;
import com.gopay.common.util.SendMail;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 民生i支付手动发起下载对账文件
 * 
 * @IPayAdDownloadOrderController.java
 * @author lilili
 * @2016-10-31 下午1:27:13 www.gopay.com.cn Inc.All rights reserved.
 */
@Controller
@Scope("prototype")
public class IPayAdDownloadOrderController {

	private static Logger logger = LoggerFactory
			.getLogger(IPayAdDownloadOrderController.class);

	@Resource(name = "ipayDayEndConfig")
	private Map<String, String> ipayDayEndConfig;

	@Resource(name = "bankClient")
	private BankInteractRemoteService bankClient;

	/**
	 * 
	 * @param HttpServletRequest
	 * @param HttpServletResponse
	 * @return ModelAndView
	 */
	@RequestMapping(value = "/iPayDownloadOrder", method = { RequestMethod.GET })
	protected void execute(HttpServletRequest request,
			HttpServletResponse response) {
		// 对账单文件名格式：ipayBill-20160530.txt
		// 对账单文件夹：/usr/local/ciecc/bankFiles/IPAY/
		// 1.检查文件夹里是否已有昨天对账单文件
		// 2.如果没有则接口查对账单
		// 3.将对账单形成文件放在文件夹里
		// 4.作为附件发送邮件
		logger.error("IPayAdDownloadOrderController: start ");
		try {
			// 生成对账单文件所需参数
			String locpath = ipayDayEndConfig.get("locpath");
			// String fTime = DateUtils.getYesterday();
			String fTime = request.getParameter("data");

			String fName = "ipayBill-" + fTime + ".txt";
			List sendFile = new ArrayList();
			List names = new ArrayList();
			String messageText = "";

			// 判断本地服务器是否存在代扣对账文件
			if (!(new File(locpath + fName).exists())) {
				// 如果不存在对账文件，查对账单并生成文件
				String content = getIpayadjust(fTime);
				boolean flag = string2File(content, locpath + fName);
				if (flag) {
					names.add(fName);
					logger.error("IPayAdDownloadOrderController " + fName
							+ " 对账文件生成成功!");
					
				} else {
					logger.error("IPayAdDownloadOrderController " + fName
							+ " 对账文件生成失败!");
					return;
				}
			} else {
				logger.error("IPayAdDownloadOrderController " + fName
						+ " 对账文件已存在!");
			}

			// 若对账文件全部为空，则邮件内容标明
			if (names.size() < 1) {
				logger.error("IPayAdDownloadOrderController: i支付对账文件为null或本地已成功下载!");
				return;
			} else {
				messageText = fTime + ": i支付对账文件见附件!" + fName;
				for (int i = 0; i < names.size(); i++) {
					sendFile.add(locpath + (String) names.get(i));
				}
			}
			String subject = "i支付对账文件";
			String[] cc = ipayDayEndConfig.get("sendmail.cc").split(","); // 获取多个抄送人
			List ccList = Arrays.asList(cc);

			logger.error("sendMessage  config:--host:"
					+ ipayDayEndConfig.get("sendmail.host") + "----sender:"
					+ ipayDayEndConfig.get("sendmail.sender") + "----username:"
					+ ipayDayEndConfig.get("sendmail.username")
					+ "----password:"
					+ ipayDayEndConfig.get("sendmail.password")
					+ "----receiver:"
					+ ipayDayEndConfig.get("sendmail.receiver"));
			// 发送邮件
			SendMail.sendMessage(ipayDayEndConfig.get("sendmail.host"),
					ipayDayEndConfig.get("sendmail.sender"),
					ipayDayEndConfig.get("sendmail.username"),
					ipayDayEndConfig.get("sendmail.password"),
					ipayDayEndConfig.get("sendmail.receiver"), subject,
					messageText, "text/html;charset=gb2312", ccList, sendFile,
					names);
			logger.error("------i支付发送邮件成功--------");

		} catch (Exception e) {
			logger.error("IPayAdDownloadOrderController error: ", e);
		}
	}

	/**
	 * 接口查对账单
	 *
	 * @return
	 */
	private String getIpayadjust(String ftime) {
		IpayMessage message = new IpayMessage();
		message.setBank(BankConstants.BANK_LOGO_IPAY);
		message.setTradeType(2);

		message.setSettleDate(ftime);
		Result result = bankClient.dayend(message);
		String content = (String) result.getDefaultModel();
		return content;
	}

	/**
	 * 生成数据文件
	 *
	 * @param filePath
	 *            写入文件的路径
	 * @param content
	 *            写入的字符串内容
	 * @return
	 */
	public boolean string2File(String content, String filePath) {
		BufferedReader bufferedReader = null;
		BufferedWriter bufferedWriter;
		boolean flag = true;
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				file.createNewFile();
			}
			bufferedReader = new BufferedReader(new StringReader(content));
			bufferedWriter = new BufferedWriter(new FileWriter(file));
			char buffer[] = new char[1024];
			int len;
			while ((len = bufferedReader.read(buffer)) != -1) {
				bufferedWriter.write(buffer, 0, len);
			}
			bufferedWriter.flush();
			bufferedReader.close();
			bufferedWriter.close();
		} catch (IOException e) {
			logger.error(String.valueOf(e));
			flag = false;
			return flag;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					logger.error(String.valueOf(e));
				}
			}
		}
		return flag;
	}
}
